	package com.ricchieri.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.dao.interf.IOperationDao;
import com.ricchieri.filter.BasicFilter;
import com.ricchieri.filter.OperationFilter;
import com.ricchieri.model.Operation;

public class OperationDao extends GenericDao implements IOperationDao {
	private static final long serialVersionUID = -6192515176520549385L;

	@Override
	@SuppressWarnings("unchecked")
	public List<Operation> getAllOperations(BasicFilter filter) {
		Criteria criteria = criteriaAllOperation(filter);
		
		return criteria.list();
	}
	
	private Criteria criteriaAllOperation(BasicFilter filter) {
		return super.criteriaAllBasic(filter, Operation.class);
	}	

	@Override
	protected String getTableName() {
		return "operation";
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Operation> getAllOperationPaginatedByFilter(
			OperationFilter operationFilter, int startRecord) {
		Criteria criteria = criteriaAllOperations(operationFilter);
		criteria.setMaxResults(BusinessSettings.ROW_MAX_RESULT);
		criteria.setFirstResult(startRecord);
		
		return criteria.list();
	}

	@Override
	public int getAllOperationCountByFilter(OperationFilter operationFilter) {
		Criteria criteria = criteriaAllOperations(operationFilter);
		Long result = (Long)criteria.setProjection(Projections.rowCount()).uniqueResult();
		return new Integer(result.intValue());
	}

	private Criteria criteriaAllOperations(OperationFilter operationFilter) {
		Criteria criteria = super.criteriaAllBasic(operationFilter, Operation.class);
		
		if (operationFilter.getUserId() > 0){
			criteria.createAlias(getTableName().concat(".user"), "user");
			criteria.add(Restrictions.eq("user.id", operationFilter.getUserId()));
		} 
		
		return criteria;
	}
}
